import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'dart:async';
import 'dart:convert';

import '../services/ble_protocol_handler.dart';

/// 设备详情页面
/// 负责设备连接、数据通信和状态管理
class DeviceDetailPage extends StatefulWidget {
  final BluetoothDevice device;

  const DeviceDetailPage({super.key, required this.device});

  @override
  State<DeviceDetailPage> createState() => _DeviceDetailPageState();
}

class _DeviceDetailPageState extends State<DeviceDetailPage> {
  bool isConnected = false;
  bool isNotifying = false;
  bool isSending = false;
  String statusMessage = '等待连接...';
  
  // 协议相关特征
  BluetoothCharacteristic? deviceInfoChar; // 设备信息特征
  BluetoothCharacteristic? commandChar;     // 命令数据特征
  BluetoothCharacteristic? responseChar;    // 响应数据特征
  
  // 数据重组缓冲区
  List<int> receivedDataBuffer = [];
  Map<int, List<int>> dataPackets = {};
  int? expectedTotalPackets;
  
  // 新增：连接与自动同步相关状态
  bool _autoReconnect = true;
  bool _isConnecting = false;
  int? negotiatedMtu;
  Timer? _autoSyncTimer;
  bool _autoSync = false;
  int _autoSyncIntervalSec = 60;
  
  late StreamSubscription connectionStateSubscription;
  StreamSubscription? responseSubscription;

  @override
  void initState() {
    super.initState();
    // 监听连接状态
    connectionStateSubscription = widget.device.connectionState.listen((state) {
      setState(() {
        isConnected = state == BluetoothConnectionState.connected;
      });

      if (state == BluetoothConnectionState.connected) {
        statusMessage = '连接成功，正在发现服务...';
        _discoverAndSetupServices();
      } else {
        statusMessage = '已断开连接';
        _resetConnectionState();
        _stopAutoSync();
        if (_autoReconnect) {
          Future.delayed(const Duration(seconds: 1), () {
            if (!_isConnecting) {
              _connect();
            }
          });
        }
      }
    });

    // 尝试连接
    _connect();
  }

  void _resetConnectionState() {
    deviceInfoChar = null;
    commandChar = null;
    responseChar = null;
    isNotifying = false;
    receivedDataBuffer.clear();
    dataPackets.clear();
    expectedTotalPackets = null;
    responseSubscription?.cancel();
  }

  @override
  void dispose() {
    connectionStateSubscription.cancel();
    responseSubscription?.cancel();
    _autoSyncTimer?.cancel();
    _disconnect();
    super.dispose();
  }

  void _connect() async {
    try {
      setState(() {
        statusMessage = '正在连接...';
      });
      _autoReconnect = true;
      _isConnecting = true;
      await widget.device.connect();
      // 协商更大的MTU以提升吞吐与稳定性
      try {
        int mtu = await widget.device.requestMtu(185);
        negotiatedMtu = mtu;
        print('MTU协商成功: $mtu');
      } catch (e) {
        print('MTU协商失败: $e');
      }
      _isConnecting = false;
    } catch (e) {
      print('连接错误: $e');
      statusMessage = '连接失败: $e';
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('连接失败: $e')),
      );
      _isConnecting = false;
    }
  }

  void _disconnect() async {
    try {
      _autoReconnect = false;
      _stopAutoSync();
      await widget.device.disconnect();
    } catch (e) {
      print('断开连接错误: $e');
    }
  }



  void _discoverAndSetupServices() async {
    try {
      List<BluetoothService> services = await widget.device.discoverServices();
      
      // 打印所有发现的服务和特征，用于调试
      print('发现的服务数量: ${services.length}');
      for (BluetoothService service in services) {
        String serviceUuid = service.uuid.toString();
        print('服务UUID: $serviceUuid');
        print('服务特征数量: ${service.characteristics.length}');
        
        for (BluetoothCharacteristic characteristic in service.characteristics) {
          String charUuid = characteristic.uuid.toString();
          print('  特征UUID: $charUuid, 属性: ${characteristic.properties}');
        }
      }
      
      // 查找协议相关服务和特征 (Service UUID: 0x1849)
      // 注意：Flutter Blue Plus返回的UUID已经是16位格式，直接使用即可
      String targetServiceUuid = '1849';
      
      // 打印目标UUID用于调试
      print('目标服务UUID: $targetServiceUuid');
      print('数据特征UUID: 2a4f');
      print('命令特征UUID: 2a50');
      
      for (BluetoothService service in services) {
        String serviceUuid = service.uuid.toString().toLowerCase();
        
        // 使用精确匹配，直接比较16位UUID
        if (serviceUuid.contains(targetServiceUuid.toLowerCase())) {
          print('找到目标服务: $serviceUuid');
          
          // 查找特征 - 直接使用16位UUID进行匹配
          for (BluetoothCharacteristic characteristic in service.characteristics) {
            String charUuid = characteristic.uuid.toString().toLowerCase();
            
            if (charUuid.contains('2a4f')) { // 通用数据特征（通知/读取）
              responseChar = characteristic;
              print('找到数据特征 (notify): $charUuid');
            } else if (charUuid.contains('2a50')) { // 命令数据特征（写）
              commandChar = characteristic;
              print('找到命令特征 (write): $charUuid');
            }
          }
        }
      }
      
      // 检查是否找到所有必需的特征
      if (commandChar != null && responseChar != null) {
        // 打印特征属性信息，用于调试
        print('命令特征属性:');
        print('  - write: ${commandChar!.properties.write}');
        print('  - writeWithoutResponse: ${commandChar!.properties.writeWithoutResponse}');
        print('  - notify: ${commandChar!.properties.notify}');
        print('  - read: ${commandChar!.properties.read}');
        
        print('响应特征属性:');
        print('  - write: ${responseChar!.properties.write}');
        print('  - writeWithoutResponse: ${responseChar!.properties.writeWithoutResponse}');
        print('  - notify: ${responseChar!.properties.notify}');
        print('  - read: ${responseChar!.properties.read}');
        
        statusMessage = '服务初始化完成，可以开始通信';
        _setupResponseNotification();
      } else {
        statusMessage = '未找到所有必需的特征，请检查设备UUID匹配 (1849/2a4f/2a50)';
        print('服务发现失败详情:');
        print('命令特征: ${commandChar != null ? "找到" : "未找到"}');
        print('响应特征: ${responseChar != null ? "找到" : "未找到"}');
      }
      
    } catch (e) {
      print('发现服务错误: $e');
      statusMessage = '服务发现失败: $e';
    }
  }

  void _setupResponseNotification() async {
    if (responseChar == null || !responseChar!.properties.notify) {
      print('响应特征不支持通知');
      return;
    }
    
    try {
      print('开始设置通知...');
      
      // 简单设置通知，不添加重试机制
      await responseChar!.setNotifyValue(true);
      
      // 设置监听器
      responseSubscription = responseChar!.value.listen((value) {
        print('收到通知数据: ${value.length} 字节');
        _processResponseData(value);
      });
      
      isNotifying = true;
      print('响应通知已启用');
    } catch (e) {
      print('设置通知错误: $e');
      // 通知设置失败，但不影响其他功能
      setState(() {
        statusMessage = '连接成功，通知功能不可用，但可以手动读取数据';
      });
    }
  }
  


  void _processResponseData(List<int> data) {
    // 解析响应帧
    Map<String, dynamic>? response = BLEProtocolHandler.parseResponseFrame(data);
    
    if (response != null) {
      int type = response['type'];
      int packetIndex = response['packetIndex'];
      int info = response['info'];
      
      switch (type) {
        case BLEProtocolHandler.RESP_TYPE_ACK:
          print('收到数据确认，包序号: $packetIndex');
          break;
        case BLEProtocolHandler.RESP_TYPE_RETRANSMIT:
          print('收到重传请求，包序号: $packetIndex');
          // 处理重传逻辑
          break;
        case BLEProtocolHandler.RESP_TYPE_COMPLETE:
          print('数据传输完成，信息: $info');
          setState(() {
            statusMessage = '数据传输完成';
            isSending = false;
          });
          break;
        case BLEProtocolHandler.RESP_TYPE_ERROR:
          print('收到错误响应，包序号: $packetIndex, 错误码: $info');
          setState(() {
            statusMessage = '传输错误: $info';
            isSending = false;
          });
          break;
      }
    } else {
      print('无效的响应帧');
    }
  }

  void _sendTestData() async {
    if (commandChar == null || isSending) return;
    
    setState(() {
      isSending = true;
      statusMessage = '正在发送测试数据...';
    });
    
    try {
      // 创建测试数据
      List<int> testData = utf8.encode('这是一条测试数据，来自Flutter客户端');
      
      // 发送数据
      bool success = await BLEProtocolHandler.sendLargeData(
        commandChar!, 
        testData, 
        BLEProtocolHandler.CMD_TYPE_DATA
      );
      
      if (success) {
        print('测试数据发送成功');
        setState(() {
          statusMessage = '测试数据发送成功';
          isSending = false;
        });
      } else {
        setState(() {
          statusMessage = '测试数据发送失败';
          isSending = false;
        });
      }
    } catch (e) {
      print('发送测试数据错误: $e');
      setState(() {
        statusMessage = '发送失败: $e';
        isSending = false;
      });
    }
  }

  void _sendLargeDataTest() async {
    if (commandChar == null || isSending) return;
    
    setState(() {
      isSending = true;
      statusMessage = '正在发送大数据包...';
    });
    
    try {
      // 创建大于MTU的测试数据
      List<int> largeData = [];
      for (int i = 0; i < 1000; i++) {
        largeData.add((i & 0xFF)); // 添加1000字节数据
      }
      
      // 发送大数据
      bool success = await BLEProtocolHandler.sendLargeData(
        commandChar!, 
        largeData, 
        BLEProtocolHandler.CMD_TYPE_DATA
      );
      
      if (success) {
        print('大数据包发送成功');
        setState(() {
          statusMessage = '大数据包发送成功';
          isSending = false;
        });
      } else {
        setState(() {
          statusMessage = '大数据包发送失败';
          isSending = false;
        });
      }
    } catch (e) {
      print('发送大数据包错误: $e');
      setState(() {
        statusMessage = '发送失败: $e';
        isSending = false;
      });
    }
  }

  void _startAutoSync() {
    if (_autoSyncTimer != null) {
      _autoSyncTimer!.cancel();
    }
    
    _autoSyncTimer = Timer.periodic(
      Duration(seconds: _autoSyncIntervalSec),
      (timer) {
        if (isConnected && !isSending) {
          _sendTimeSync();
        }
      },
    );
    
    setState(() {
      _autoSync = true;
    });
  }

  void _stopAutoSync() {
    _autoSyncTimer?.cancel();
    _autoSyncTimer = null;
    setState(() {
      _autoSync = false;
    });
  }

  void _sendTimeSync() async {
    if (commandChar == null || isSending) return;
    
    try {
      // 获取当前时间
      DateTime now = DateTime.now();
      // 转换为Unix时间戳（毫秒）- 协议要求64位毫秒时间戳
      int timestamp = now.millisecondsSinceEpoch;
      
      // 获取时区偏移（分钟）- 中国标准时间为+480分钟
      int timezoneOffsetMinutes = now.timeZoneOffset.inMinutes;
      
      // 构建符合协议规范的13字节payload
      List<int> timeData = [];
      
      // 1. 子命令ID：0x01（SetTime）
      timeData.add(0x01);
      
      // 2. 时间戳：8字节（64位，小端序）
      timeData.add(timestamp & 0xFF);
      timeData.add((timestamp >> 8) & 0xFF);
      timeData.add((timestamp >> 16) & 0xFF);
      timeData.add((timestamp >> 24) & 0xFF);
      timeData.add((timestamp >> 32) & 0xFF);
      timeData.add((timestamp >> 40) & 0xFF);
      timeData.add((timestamp >> 48) & 0xFF);
      timeData.add((timestamp >> 56) & 0xFF);
      
      // 3. 时区偏移：2字节（小端序）
      timeData.add(timezoneOffsetMinutes & 0xFF);
      timeData.add((timezoneOffsetMinutes >> 8) & 0xFF);
      
      // 4. 保留字段：1字节（填0）
      timeData.add(0x00);
      
      // 5. 附加标志：1字节（bit0=平滑校时，其余保留为0）
      timeData.add(0x01); // 启用平滑校时
      
      // 发送时间同步命令
      bool success = await BLEProtocolHandler.sendLargeData(
        commandChar!, 
        timeData, 
        BLEProtocolHandler.CMD_TYPE_TIME_SYNC
      );
      
      if (success) {
        print('时间同步发送成功: 时间戳=$timestamp, 时区偏移=$timezoneOffsetMinutes分钟');
      } else {
        print('时间同步发送失败');
      }
    } catch (e) {
      print('时间同步错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('设备详情 - ${widget.device.name}'),
        actions: [
          IconButton(
            icon: Icon(isConnected ? Icons.bluetooth_connected : Icons.bluetooth_disabled),
            onPressed: isConnected ? _disconnect : _connect,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 连接状态
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          isConnected ? Icons.check_circle : Icons.error,
                          color: isConnected ? Colors.green : Colors.red,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          isConnected ? '已连接' : '未连接',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: isConnected ? Colors.green : Colors.red,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Text('设备ID: ${widget.device.id}'),
                    Text('状态: $statusMessage'),
                    if (negotiatedMtu != null) Text('MTU: $negotiatedMtu'),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 控制按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton(
                  onPressed: isConnected && !isSending ? _sendTestData : null,
                  child: const Text('发送测试数据'),
                ),
                ElevatedButton(
                  onPressed: isConnected && !isSending ? _sendLargeDataTest : null,
                  child: const Text('发送大数据包'),
                ),
                ElevatedButton(
                  onPressed: isConnected && !isSending ? _sendTimeSync : null,
                  child: const Text('时间同步'),
                ),
                ElevatedButton(
                  onPressed: isConnected ? (_autoSync ? _stopAutoSync : _startAutoSync) : null,
                  child: Text(_autoSync ? '停止自动同步' : '开始自动同步'),
                ),
              ],
            ),
            
            const SizedBox(height: 16),
            
            // 自动同步设置
            if (isConnected)
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '自动同步设置',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          const Text('同步间隔（秒）:'),
                          const SizedBox(width: 8),
                          SizedBox(
                            width: 80,
                            child: TextField(
                              decoration: const InputDecoration(
                                border: OutlineInputBorder(),
                                contentPadding: EdgeInsets.symmetric(horizontal: 8),
                              ),
                              keyboardType: TextInputType.number,
                              onChanged: (value) {
                                int? interval = int.tryParse(value);
                                if (interval != null && interval > 0) {
                                  _autoSyncIntervalSec = interval;
                                }
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            
            // 发送状态指示器
            if (isSending)
              const Padding(
                padding: EdgeInsets.only(top: 16),
                child: Row(
                  children: [
                    SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    ),
                    SizedBox(width: 8),
                    Text('正在发送数据...'),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }
}